package com.oinux.playhelper.receiver;

import java.sql.SQLException;
import java.util.List;

import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.PreparedQuery;
import com.j256.ormlite.stmt.QueryBuilder;
import com.oinux.playhelper.db.DatabaseHelper;
import com.oinux.playhelper.entity.AppInfo;
import com.oinux.playhelper.entity.Constants;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.util.Log;

public class AppRemoveReceiver extends BroadcastReceiver {

	private static final String TAG = "remove.app...";

	@Override
	public void onReceive(Context context, Intent intent) {
		if (intent.getAction().equals(Constants.ACTION_PACKAGE_REMOVED)) {
			Log.v(TAG, "应用卸载..");
			checkApp(context); 
		}
	}

	private void checkApp(Context context) {
		try {
			DatabaseHelper databaseHelper = OpenHelperManager.getHelper(
					context, DatabaseHelper.class);
			List<PackageInfo> packages = context.getPackageManager()
					.getInstalledPackages(0);
			Dao<AppInfo, Integer> appInfoDao = databaseHelper.getAppInfoDao();
			QueryBuilder<AppInfo, Integer> queryBuilder = appInfoDao
					.queryBuilder();
			queryBuilder.where().eq("isInstall", true);
			PreparedQuery<AppInfo> preparedQuery = queryBuilder.prepare();
			List<AppInfo> appInfoList = appInfoDao.query(preparedQuery);
			for (AppInfo appInfo : appInfoList) {
				boolean removed = true;
				for (PackageInfo packageInfo : packages) {
					if (appInfo.getPackageName()
							.equals(packageInfo.packageName)) {
						removed = false;
						break;
					}
				}
				if (removed) {
					appInfo.setInstall(false);
					appInfo.setRunning(false);
					appInfo.setRunTime(0);
					appInfo.setMemSize(0);
					appInfo.setPid(0);
					appInfo.setUid(0);
					appInfoDao.update(appInfo);
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}